package org.xx.armory.spring5.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

import static org.xx.armory.spring5.mvc.ModelUtils.JSON_VIEW;
import static org.xx.armory.spring5.mvc.ModelUtils.buildJsonView;
import static org.xx.armory.spring5.security.WebSecurityConfig.ROLE_ADMIN;

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/current")
    public ModelAndView currentUser(
            Authentication token
    ) {
        final var result = new ModelAndView(JSON_VIEW);

        if (token != null) {
            result.addObject("name", token.getName());
            result.addObject("authenticated", token.isAuthenticated());
        } else {
            result.addObject("name", "");
            result.addObject("authenticated", false);
        }

        return result;
    }

    @GetMapping("/is-admin")
    public ModelAndView isAdmin(
            Authentication token
    ) {
        final var result = token.getAuthorities()
                                .stream()
                                .map(GrantedAuthority::getAuthority)
                                .anyMatch(a -> Objects.equals(a, ROLE_ADMIN));

        return buildJsonView(result);
    }
}
